package com.hzpd.hainan.module.usercenter.acticity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.hzpd.hainan.R;
import com.hzpd.hainan.api.InterfaceJsonfile;
import com.hzpd.hainan.app.BaseActivity;
import com.hzpd.hainan.app.ToolBarActivity;
import com.hzpd.hainan.config.CODE;
import com.hzpd.hainan.model.news.NewsBean;
import com.hzpd.hainan.model.usercenter.CollectBean;
import com.hzpd.hainan.model.usercenter.CollectEntity;
import com.hzpd.hainan.model.usercenter.EmptyEntity;
import com.hzpd.hainan.model.video.VideoItemBean;
import com.hzpd.hainan.module.news.activity.NewsHtmlDetailActivity;
import com.hzpd.hainan.module.news.activity.NewsZhuanTiActivity;
import com.hzpd.hainan.module.usercenter.adapter.CollectionAdapter;
import com.hzpd.hainan.module.video.activity.VideoDetailActivity;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.AAnim;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.Lunar;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.TUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class CollectionActivity extends ToolBarActivity {

    @BindView(R.id.tv_empty_collection_activity)
    TextView tv_empty_collotion_activity;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.ptrlistview_activity_collection)
    PullToRefreshListView ptrlistview;

    @BindView(R.id.collection_list_tv)
    TextView collection_list_tv;
    private CollectionAdapter adapter;
    private List<CollectBean> list;
    private int Page = 1;
    private static final int PageSize = 15;
    private boolean mFlagRefresh = true;//刷新还是加载

    @Override
    public void initView() {
        if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
            tv_title.setText("我的收藏");
            collection_list_tv.setText("收藏列表");
            tv_empty_collotion_activity.setText("没有收藏");
        }else{
            tv_title.setText("བསྡུ་ཉར།");
            collection_list_tv.setText("རེའུ་མིག");
            tv_empty_collotion_activity.setText("བསྡུ་གསོག་མེད་པ།");
        }
    }

    @Override
    public String initToolBarTitle() {
        return null;
    }

    @Override
    public int setMyContentView() {
        return R.layout.activity_collection;
    }

    @Override
    public void initData() {
        super.initData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }



    private void init() {
        list = new ArrayList<>();
        getCollectionInfoFromServer();
        ptrlistview.setEmptyView(tv_empty_collotion_activity);
        ptrlistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        adapter = new CollectionAdapter(activity);
        ptrlistview.setAdapter(adapter);
        ptrlistview.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mycollectionItemclick(adapterView, view, i, l);
            }
        });
        ptrlistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                ptrlistview.getLoadingLayoutProxy().setPullLabel("下拉刷新");
                Page = 1;
                mFlagRefresh = true;
                getCollectionInfoFromServer();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                ptrlistview.getLoadingLayoutProxy().setPullLabel("");
                Page++;
                mFlagRefresh = false;
                getCollectionInfoFromServer();
            }
        });
//        ptrlistview.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                ptrlistview.setRefreshing(true);
//            }
//        }, 500);

        ptrlistview.getRefreshableView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> adapterView, final View view, final int position, final long l) {
                LogUtils.e("position----" + position);
                if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
                    new AlertDialog.Builder(activity)
                            .setTitle("确定删除？")
                            .setCancelable(true)
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    disMissDialog();
                                }
                            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ptrlistview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptrlistview.setRefreshing(true);
                                }
                            }, 500);

                            mycollectionItemLongclick(adapterView, view, position, l);
                        }
                    }).show();
                }else{
                    new AlertDialog.Builder(activity)
                            .setTitle("确定删除？")
                            .setCancelable(true)
                            .setNegativeButton("ཕྱིར་འཐེན།", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    disMissDialog();
                                }
                            }).setPositiveButton("གཏན་འཁེལ།", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ptrlistview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptrlistview.setRefreshing(true);
                                }
                            }, 500);

                            mycollectionItemLongclick(adapterView, view, position, l);
                        }
                    }).show();
                }
                return true;
            }
        });
    }

    private void mycollectionItemLongclick(AdapterView<?> adapterView, View view, int i, long l) {
        CollectBean cb = (CollectBean) adapter.getItem(i - 1);
        Map map = new HashMap();
        map.put("uid", spu.getUser().getUid());
        map.put("fid", cb.getId());
        LogUtils.e(spu.getUser().getUid() + "-----" + cb.getId());
        Factory.provideHttpService().deletecollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntity, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntity emptyEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntity>() {
                    @Override
                    public void call(EmptyEntity emptyEntity) {
                        disMissDialog();
                        ptrlistview.onRefreshComplete();
                        TUtils.toast(emptyEntity.msg);
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }


    private void getCollectionInfoFromServer() {
        Map<String, String> map = new HashMap<>();
        map.put("Page", Page + "");
        map.put("PageSize", PageSize + "");
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("uid", spu.getUser().getUid());
        Factory.provideHttpService().collection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<CollectEntity, Boolean>() {
                    @Override
                    public Boolean call(CollectEntity collectEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CollectEntity>() {
                    @Override
                    public void call(CollectEntity collectEntity) {
                        LogUtils.e("code--" + collectEntity.code);
                        ptrlistview.onRefreshComplete();
                        if ("200".equals(collectEntity.code)) {
                            LogUtils.e("code--" + collectEntity.msg);
                            LogUtils.e("code--" + collectEntity.data.getCount());
                            LogUtils.e("code--" + collectEntity.data.getList().size());
                            addDataList(collectEntity.data.getList());

                            LogUtils.e(list.size() + "");
                        } else if ("209".equals(collectEntity.code)) {
                            adapter.clear();
                            adapter.removeOld();
                            list.clear();
                            adapter.notifyDataSetChanged();
                        } else {
                            if (!mFlagRefresh) {
                                Page--;
                            }
                        }
                        mFlagRefresh = false;
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable--" + throwable.getMessage());
                    }
                });


    }

    private void addDataList(List<CollectBean> mlist) {
        adapter.appendData(mlist, true);
        LogUtils.e(list.size() + "");
        adapter.notifyDataSetChanged();
        ptrlistview.setAdapter(adapter);
    }

    private void mycollectionItemclick(AdapterView<?> adapterView, View view, int i, long l) {
        CollectBean cb = (CollectBean) adapter.getItem(i - 1);
        Intent intent = new Intent();
        intent.putExtra("from", "collection");
        NewsBean nb = new NewsBean();
        nb.setNid(cb.getData().getContentid());
        nb.setImgs(cb.getData().getImgs());
        boolean flag = false;//是否是预定类型
        //跳转脚标）1新闻  2图集  3视频 4html5
        LogUtils.e("type-->" + cb.getType());
        if ("1".equals(cb.getType())) {

            intent.putExtra("newbean", nb);
            flag = true;
            intent.setClass(CollectionActivity.this, NewsHtmlDetailActivity.class);
        } else if ("4".equals(cb.getType())) {
            intent.putExtra("newbean", nb);
            flag = true;
            intent.setClass(CollectionActivity.this, NewsZhuanTiActivity.class);
        } else if ("3".equals(cb.getType())) {
            VideoItemBean videoItemBean = new VideoItemBean();
            videoItemBean.setVid(cb.getData().getContentid());
            videoItemBean.setTitle(cb.getData().getTitle());
            videoItemBean.setVideourl(cb.getData().getVideourl());
            intent.putExtra("videoItemBean", videoItemBean);
            flag = true;
            intent.setClass(this, VideoDetailActivity.class);
        }
        if (flag) {
            startActivity(intent);
            AAnim.startScreen(activity);
        }
    }


}
